<?php

namespace app\admin\controller;

use app\admin\library\AliyunSendSms;
use app\admin\model\Assistant;
use app\admin\model\ManagementSms;
use app\common\controller\Backend;
use app\common\model\Agent;
use app\common\model\Serial;
use EasyWeChat\Factory;
use PHPExcel;
use think\Config;
use think\Db;
use workflow\work;
require_once(ROOT_PATH.'extend/workflow/msg/work.php');

/**
 * 网络销售订单
 *
 * @icon fa fa-circle-o
 */
class Management extends Backend
{

    /**
     * Management模型对象
     * @var \app\admin\model\Management
     */
    protected $model = null;
    protected $Model2020 = null;
    private $source = '';
    protected $toUser = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Management;
        $this->Model2020 = connection_2020();
        $this->view->assign("GiftList", $this->model->getGiftList());
        $site = Config::get("site");
        $site['invoice'] = json_decode($site['invoice'],true);
        $site['invoice'] = array_column($site['invoice'],'name');
        $this->toUser = implode('|',$site['invoice']);
    }

    private function msg($source)
    {
        return false;
        $workApp = new work();
        $array = [
            'touser' => $this->toUser,
            'toparty' => '',
            'totag' => '',
            'content' => '订单来源:' . $source . ' 有新的数据',
        ];
        $respon = $workApp->send('text', $array);
    }

    private function msgOperator($user)
    {
        $workApp = new work();
        $array = [
            'touser' => $user,
            'toparty' => '',
            'totag' => '',
            'content' => '您导入的订单已经发货',
        ];
        $respon = $workApp->send('text', $array);
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->searchFields = 'id,orderid,consignee,consigneePhone,goods,courierBut';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach ($list as &$value) {
                if ($value['gifts']) {
                    $value['version'] .= '+' . $value['gifts'];
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['订单编号'] = 'orderid';//订单编号
        $fieldArr['快递单号'] = 'courierBut';//快递单号
        $fieldArr['快递方式'] = 'deliveryForm';//快递公司

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $update = [];
        $operator = [];
        $rowIds = [];
        $num = 0;
        Db::startTrans();
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if (!isset($row['orderid'])) {
                $this->error(__('订单编号标题错误 ~'));
            }
            $row = array_filter($row);
            if ($row) {
                if(!$row['courierBut']) $this->error('第'.$currentRow.'行,没有快递单号！。');
                $update[] = $row;
                if (!$rowGet = $this->model->get(['orderid' => $row['orderid']])) {
                    Db::rollback();
                    $this->error(__('订单编号:' . $row['orderid'] . '不存在！'));
                }
                $operator[] = $rowGet->operator;
                $rowIds[] = $rowGet->id;
                $rowGet->courierBut = $row['courierBut'];
                $rowGet->deliveryForm = $row['deliveryForm'] ? $row['deliveryForm'] : '韵达快递';
                $rowGet->orderStatus = '已发货';
                $num += $rowGet->save();

            }
        }
        if ($num == 0) {
            Db::rollback();
            $this->error(__('没有数据可以更新！'));
        }
        if (!$update) {
            Db::rollback();
            $this->error(__('No rows were updated'));
        }
        //数组去重  | 拆分
        $operator = array_filter($operator);
        $operator = implode('|', $operator);
        $this->msgOperator($operator);
        Db::commit();
        $this->success();
    }

    public function importJl()
    {
        ini_set('max_execution_time', '0');
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        $fieldArr['下单日期'] = 'ordertime';
        $fieldArr['金额'] = 'amount';
        $fieldArr['数量'] = 'num';
        $fieldArr['订单编号'] = 'orderid';//订单编号
        $fieldArr['数据来源'] = 'source';//订单编号
        $fieldArr['代理商ID'] = 'agent_id';//代理商id
        $fieldArr['商品名称'] = 'goods';//代理商id
        $fieldArr['版本'] = 'version';//代理商id
        $fieldArr['A学习书'] = 'xuexishu';//A学习书
        $fieldArr['B练习书'] = 'lianxishu';//B练习书
        $fieldArr['C素材书'] = 'cucaishu';//C素材书
        $fieldArr['字词句手册'] = 'zicujushouce';//字词句手册
        $fieldArr['年级阅读'] = 'nianjiyuedu';//年级阅读
        $fieldArr['教案'] = 'jiaoan';//教案
        $fieldArr['数学'] = 'shyxue';//数学
        $fieldArr['收件人'] = 'consignee';//数学
        $fieldArr['收件人电话'] = 'consigneePhone';//数学
        $fieldArr['收件人地址'] = 'consigneeAddress';//address
        $fieldArr['快递方式'] = 'deliveryForm';//快递公司
        $fieldArr['快递单号'] = 'courierBut';//快递单号
        $fieldArr['订单状态'] = 'orderStatus';//快递单号
        $fieldArr['备注'] = 'remake';//remake

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }

        $rowIds = [];
        $update = [];
        $data = [];
        $num = 0;
        $nums = 0;
        Db::startTrans();
        $error = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if (!isset($row['orderid'])) {
                $this->error(__('订单编号标题错误 ~'));
            }
            if (!isset($row['agent_id'])) {
                $this->error(__('代理商ID标题错误 ~'));
            }
            $row = array_filter($row);
            if ($row) {
                $row['product'] = '';
            }
            if (isset($row['xuexishu'])) {
                $row['product'] .= $row['xuexishu'] . ',';
                unset($row['xuexishu']);
            }
            if (isset($row['lianxishu'])) {
                $row['product'] .= $row['lianxishu'] . ',';
                unset($row['lianxishu']);
            }
            if (isset($row['cucaishu'])) {
                $row['product'] .= $row['cucaishu'] . ',';
                unset($row['cucaishu']);
            }
            if (isset($row['zicujushouce'])) {
                $this->wordWords($row['zicujushouce'],16);
                $row['product'] .= $row['zicujushouce'] . ',';
                unset($row['zicujushouce']);
            }
            if (isset($row['nianjiyuedu'])) {
                $row['product'] .= $row['nianjiyuedu'] . ',';
                unset($row['nianjiyuedu']);
            }
            if (isset($row['jiaoan'])) {
                $row['product'] .= $row['jiaoan'] . ',';
                unset($row['jiaoan']);
            }
            if (isset($row['shyxue'])) {
                $row['product'] .= $row['shyxue'] . ',';
                unset($row['shyxue']);
            }
            if ($row) {
                if (!isset($row['courierBut'])) {
                    Db::rollback();
                    $this->error(__('请输入快递单号！'));
                }
                if (!isset($row['deliveryForm'])) {
                    Db::rollback();
                    $this->error(__('请输入快递方式！'));
                }
                $orderIds = $this->model->where('orderid', $row['orderid'])->find();
                if($orderIds)
                {
                    Db::rollback();
                    $this->error(__('添加失败，订单号重复！'));
                }
                //添加
                if($this->model->insert($row))
                {
                    $nums+=1;
                }else{
                    Db::rollback();
                    $this->error(__('添加失败，表格有误！'));
                }
                $code = explode(',', $row['product']);
                $code = array_filter(array_unique($code));
                if(count($code) == 0)
                {
                    $this->error('第'.$currentRow.'行,没有激活码');
                }
                $result = $this->getAddress($row['consigneeAddress']);
                $diqu = str_replace("省", "", str_replace(" ", '', trim($result['result']['address_components']['province'])));
                $diqu .= str_replace("市", "", str_replace(" ", '', trim($result['result']['address_components']['city'])));
                $diqu .= $result['result']['address_components']['district'];
                unset($row['address']);
                foreach ($code as &$value) {
                    $value = str_replace("-", "", str_replace(" ", '', trim($value)));
                    if ($serial = Serial::get(['code' => $value,'send'=>0])) {
                        $serial->fahuo = $diqu;
                        $serial->sendtime = time();
                        $serial->dealer_uid = $row['agent_id'];
                        $serial->send = 1;
                        $serial->order_sn  = $row['orderid'];
                        $serial->save();
                    } else {
                        $error[] = $value;
                    }

                }

            }
        }
        Db::commit();
        $this->success('成功'.$nums.'条');
    }

    public function imports()
    {
        ini_set('max_execution_time', '0');
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['订单编号'] = 'orderid';//订单编号
        $fieldArr['代理商ID'] = 'agent_id';//代理商id
        $fieldArr['快递单号'] = 'courierBut';//快递单号
        $fieldArr['快递方式'] = 'deliveryForm';//快递公司
        $fieldArr['A学习书'] = 'xuexishu';//A学习书
        $fieldArr['B练习书'] = 'lianxishu';//B练习书
        $fieldArr['C素材书'] = 'cucaishu';//C素材书
        $fieldArr['字词句手册'] = 'zicujushouce';//字词句手册
        $fieldArr['年级阅读'] = 'nianjiyuedu';//年级阅读
        $fieldArr['教案'] = 'jiaoan';//教案
        $fieldArr['数学'] = 'shyxue';//数学
        $fieldArr['收件人地址'] = 'address';//address
        $fieldArr['备注'] = 'remake';//remake

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $rowIds = [];
        $update = [];
        $data = [];
        $num = 0;
        $nums = 0;
        Db::startTrans();
        $error = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if (!isset($row['orderid'])) {
                $this->error(__('订单编号标题错误 ~'));
            }
            if (!isset($row['agent_id'])) {
                $this->error(__('代理商ID标题错误 ~'));
            }
            $row = array_filter($row);
            if ($row) {
                $row['product'] = '';
            }
            if (isset($row['xuexishu'])) {
                //判断是否是学习书 如果不是返回
                //学习书 kumu 11  练习书 kumu 12  素材书 kemu13 教案 kemu14 年级阅读 kumu 15  字词句手册 kumu  16
//                if (!$this->getAuthType($row['xuexishu'],11)) {
//                    $this->error('第'.$currentRow.'行,学习书产品码不正确。' . $row['xuexishu']);
//                }
                $row['product'] .= $row['xuexishu'] . ',';
                unset($row['xuexishu']);
            }
            if (isset($row['lianxishu'])) {
//                if (!$this->getAuthType($row['lianxishu'],12)) {
//                    $this->error('第'.$currentRow.'行,练习书产品码不正确。' . $row['lianxishu']);
//                }
                $row['product'] .= $row['lianxishu'] . ',';
                unset($row['lianxishu']);
            }
            if (isset($row['cucaishu'])) {
//                if (!$this->getAuthType($row['cucaishu'],13)) {
//                    $this->error('第'.$currentRow.'行,素材书产品码不正确。' . $row['cucaishu']);
//                }
                $row['product'] .= $row['cucaishu'] . ',';
                unset($row['cucaishu']);
            }
            if (isset($row['zicujushouce'])) {
                $this->wordWords($row['zicujushouce'],16);
//                if (!$this->getAuthType($row['zicujushouce'],16)) {
//                    $this->error('第'.$currentRow.'行,字词句手册产品码不正确。' . $row['zicujushouce']);
//                }
                $row['product'] .= $row['zicujushouce'] . ',';
                unset($row['zicujushouce']);
            }
            if (isset($row['nianjiyuedu'])) {
//                if (!$this->getAuthType($row['nianjiyuedu'],15)) {
//                    $this->error('第'.$currentRow.'行,年级阅读产品码不正确。' . $row['nianjiyuedu']);
//                }
                $row['product'] .= $row['nianjiyuedu'] . ',';
                unset($row['nianjiyuedu']);
            }
            if (isset($row['jiaoan'])) {
//                if (!$this->getAuthType($row['jiaoan'],14)) {
//                    $this->error('第'.$currentRow.'行,教案产品码不正确。' . $row['jiaoan']);
//                }
                $row['product'] .= $row['jiaoan'] . ',';
                unset($row['jiaoan']);
            }
            if (isset($row['shyxue'])) {
//                if (!$this->getAuthType($row['shyxue'],'')) {
//                    $this->error('第'.$currentRow.'行,数学书产品码不正确。' . $row['shyxue']);
//                }
                $row['product'] .= $row['shyxue'] . ',';
                unset($row['shyxue']);
            }
            if ($row) {
                $code = explode(',', $row['product']);
                $code = array_filter(array_unique($code));
                if(count($code) == 0)
                {
                    $this->error('第'.$currentRow.'行,没有激活码');
                }
                $result = $this->getAddress($row['address']);
                $diqu = str_replace("省", "", str_replace(" ", '', trim($result['result']['address_components']['province'])));
                $diqu .= str_replace("市", "", str_replace(" ", '', trim($result['result']['address_components']['city'])));
                $diqu .= $result['result']['address_components']['district'];
                unset($row['address']);
                foreach ($code as &$value) {
                    $value2 = $value;
                    $value = str_replace("-", "", str_replace(" ", '', trim($value)));
                    if ($serial = Serial::get(['code' => $value,'send'=>0])) {
                        $serial->fahuo = $diqu;
                        $serial->sendtime = time();
                        $serial->dealer_uid = $row['agent_id'];
                        $serial->send = 1;
                        $serial->order_sn  = $row['orderid'];
                        $nums += $serial->save();
                    } else {
                        $error[] = $value2;
                    }

                }
                if (!isset($row['courierBut'])) {
                    Db::rollback();
                    $this->error(__('请输入快递单号！'));
                }
                if (!isset($row['deliveryForm'])) {
                    Db::rollback();
                    $this->error(__('请输入快递方式！'));
                }
                $update[] = $row;
//                $row['orderid'] = $this->decimalNotation($row['orderid']);
                $row['courierBut'] = $this->decimalNotation($row['courierBut']);
                if (!$rowGet = $this->model->get(['orderid' => $row['orderid']])) {
                    Db::rollback();
                    $this->error(__('订单编号:' . $row['orderid'] . '不存在！'));
                }
                if(isset($row['remake']))
                {
                    $rowGet->remake = $row['remake'] ? $row['remake']:'';
                }
                $rowIds[] = $rowGet->id;
                $rowGet->courierBut = $row['courierBut'];
                $rowGet->deliveryForm = $row['deliveryForm'] ? $row['deliveryForm'] : '韵达快递';
                $rowGet->orderStatus = '已发货';
                $rowGet->save();

                //发送短信  杨柳
//                $data['phone'][] = $rowGet['consigneePhone'];
//                $data['sign'][] = '宏达一甲';
//                $data['template'][] = ['kuaidi_name'=>'中通快递','order_sn'=>$rowGet['courierBut']];
            }
        }
        if (!$update) {
            Db::rollback();
            $this->error(__('No rows were updated'));
        }
        if(!$rowIds)
        {
            Db::rollback();
            $this->error(__('No rows were updated'));
        }
        /*
         * 短信不发送
         * $smsData = [];
        $list = $this->model->where('id', 'in', $rowIds)->select();
        foreach ($list as $index => $item) {
            //发送短信  杨柳
            $smsData['phone'][] = $item['consigneePhone'];
            $smsData['sign'][] = '宏达一甲';
            $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut']];
            if($item->send == 0)
            {
                if($this->SmsOne($smsData))
                {
                    $item->allowField(true)->isUpdate(true)->save(['send'=>1]);
                }
            }
            $smsData = [];
        }*/
        Db::commit();
        if(count($error) > 0)
        {
            $this->success('成功（'.$nums.'）条'.'失败（'.count($error).'）条','',$error);
        }
        $this->success('成功'.$nums.'条');
    }
    //上册发货导入
    public function importsc()
    {
        ini_set('max_execution_time', '0');
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['订单编号'] = 'orderid';//订单编号
        $fieldArr['代理商ID'] = 'agent_id';//代理商id
        $fieldArr['快递单号'] = 'courierBut';//快递单号
        $fieldArr['快递方式'] = 'deliveryForm';//快递公司
        $fieldArr['A学习书'] = 'xuexishu';//A学习书
        $fieldArr['B练习书'] = 'lianxishu';//B练习书
        $fieldArr['C素材书'] = 'cucaishu';//C素材书
        $fieldArr['字词句手册'] = 'zicujushouce';//字词句手册
        $fieldArr['年级阅读'] = 'nianjiyuedu';//年级阅读
        $fieldArr['教案'] = 'jiaoan';//教案
        $fieldArr['数学'] = 'shyxue';//数学
        $fieldArr['收件人地址'] = 'address';//address
        $fieldArr['备注'] = 'remake';//remake
        $fieldArr['年级'] = 'subject';//subject

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $rowIds = [];
        $update = [];
        $data = [];
        $num = 0;
        $nums = 0;
        Db::startTrans();
        $error = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }

            if (!isset($row['orderid'])) {
                $this->error(__('订单编号标题错误 ~'));
            }
            if (!isset($row['agent_id'])) {
                $this->error(__('代理商ID标题错误 ~'));
            }
            if (!isset($row['subject'])) {
                $this->error(__('导入上册请填写年级 ~'));
            }

            $row = array_filter($row);

            if ($row) {
                $row['product'] = '';
            }

            if (isset($row['xuexishu'])) {
                $type = $this->gettype_sc($row['subject'],11);

                $this->insert_sc($row['xuexishu'],$row['subject'],11,$type);
                $row['product'] .= $row['xuexishu'] . ',';
                unset($row['xuexishu']);
            }
            if (isset($row['lianxishu'])) {
                $type = $this->gettype_sc($row['subject'],12);
                $this->insert_sc($row['lianxishu'],$row['subject'],12,$type);
                $row['product'] .= $row['lianxishu'] . ',';
                unset($row['lianxishu']);
            }
            if (isset($row['cucaishu'])) {
                $type = $this->gettype_sc($row['subject'],13);
                $this->insert_sc($row['cucaishu'],$row['subject'],13,$type);
                $row['product'] .= $row['cucaishu'] . ',';
                unset($row['cucaishu']);
            }
            if (isset($row['zicujushouce'])) {
                $type = $this->gettype_sc($row['subject'],16);
                $this->insert_sc($row['zicujushouce'],$row['subject'],16,$type);
                $row['product'] .= $row['zicujushouce'] . ',';
                unset($row['zicujushouce']);
            }
            if (isset($row['nianjiyuedu'])) {
                $type = $this->gettype_sc($row['subject'],15);
                $this->insert_sc($row['nianjiyuedu'],$row['subject'],15,$type);
                $row['product'] .= $row['nianjiyuedu'] . ',';
                unset($row['nianjiyuedu']);
            }
            if (isset($row['jiaoan'])) {
                $type = $this->gettype_sc($row['subject'],14);
                $this->insert_sc($row['jiaoan'],$row['subject'],14,$type);
                $row['product'] .= $row['jiaoan'] . ',';
                unset($row['jiaoan']);
            }

            if ($row) {
                $code = explode(',', $row['product']);
                $code = array_filter(array_unique($code));
                if(count($code) == 0)
                {
                    $this->error('第'.$currentRow.'行,没有激活码');
                }
                if(!in_array($row['subject'],array(11,13,15,17,19,21))){
                    $this->error(__('导入上册请填写年级 ~'));
                }
                $result = $this->getAddress($row['address']);
                $diqu = str_replace("省", "", str_replace(" ", '', trim($result['result']['address_components']['province'])));
                $diqu .= str_replace("市", "", str_replace(" ", '', trim($result['result']['address_components']['city'])));
                $diqu .= $result['result']['address_components']['district'];
                unset($row['address']);
                foreach ($code as &$value) {
                    $value = str_replace("-", "", str_replace(" ", '', trim($value)));
                    if ($serial = Serial::get(['code' => $value,'send'=>0])) {
                        $serial->fahuo = $diqu;
                        $serial->sendtime = time();
                        $serial->dealer_uid = $row['agent_id'];
                        $serial->send = 1;
                        $serial->order_sn  = $row['orderid'];
                        $nums += $serial->save();
                    } else {
                        $error[] = $value;
                    }

                }
                if (!isset($row['courierBut'])) {
                    Db::rollback();
                    $this->error(__('请输入快递单号！'));
                }
                if (!isset($row['deliveryForm'])) {
                    Db::rollback();
                    $this->error(__('请输入快递方式！'));
                }
                $update[] = $row;
                $row['courierBut'] = $this->decimalNotation($row['courierBut']);
                if (!$rowGet = $this->model->get(['orderid' => $row['orderid']])) {
                    Db::rollback();
                    $this->error(__('订单编号:' . $row['orderid'] . '不存在！'));
                }
                if(isset($row['remake']))
                {
                    $rowGet->remake = $row['remake'] ? $row['remake']:'';
                }
                $rowIds[] = $rowGet->id;
                $rowGet->courierBut = $row['courierBut'];
                $rowGet->deliveryForm = $row['deliveryForm'] ? $row['deliveryForm'] : '韵达快递';
                $rowGet->orderStatus = '已发货';
                $rowGet->save();
            }
        }
        if (!$update) {
            Db::rollback();
            $this->error(__('No rows were updated'));
        }
        if(!$rowIds)
        {
            Db::rollback();
            $this->error(__('No rows were updated'));
        }
        Db::commit();
        if(count($error) > 0)
        {
            $this->success('成功（'.$nums.'）条'.'失败（'.count($error).'）条','',$error);
        }
        $this->success('成功'.$nums.'条');
    }

    public function importYz()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['订单号'] = 'orderid';//订单编号
        $fieldArr['订单状态'] = 'delivery';//发货情况
        $fieldArr['支付流水号'] = 'pay_nb';//商户订单号
        $fieldArr['收货人/提货人'] = 'consignee';//收件人
        $fieldArr['收货人手机号/提货人手机号'] = 'consigneePhone';//收件人电话
        $fieldArr['详细收货地址/提货地址'] = 'consigneeAddress';//收件人地址
        $fieldArr['全部商品名称'] = 'goods';//商品名称
        $fieldArr['版本'] = 'version';//版本
        $fieldArr['商品种类数'] = 'num';//数量
        $fieldArr['商品金额合计'] = 'amount';//金额
        $fieldArr['运费'] = 'courierFees';//快递费用
        $fieldArr['订单配送方式'] = 'deliveryForm';//快递形式
        $fieldArr['商家订单备注'] = 'salesman';//业务员
        $fieldArr['买家备注'] = 'salesman2';//备注
        $fieldArr['订单实付金额'] = 'wechat';//有赞
        $fieldArr['订单创建时间'] = 'ordertime';//订单创建时间
        $fieldArr['买家付款时间'] = 'paytime';//订单创建时间

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        $order_sn = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : trim($val);
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if (!isset($row['orderid'])) {
                $this->error(__('请导入有赞的订单！'));
            }
            $str = '';
            if ($row) {
                $str = $row['salesman'] ? "商家备注：".$row['salesman']:'';
                $str .= $row['salesman2'] ? "买家备注：".$row['salesman2']:'';
                $this->source = '有赞';
                $row['source'] = '有赞';
                $row['remake'] = $str;
                $row['deliveryForm'] = '韵达快递';
                $row['agent_id'] = '83';
                $row['operator'] = $this->auth->userid;//导入人
                $row['ordertime'] = $row['ordertime'] ? $this->excelTime($row['ordertime']) : '';
                $row['paytime'] = $row['paytime'] ? $this->excelTime($row['paytime']) : '';
                $order_sn[] = $row['orderid'];
                unset($row['salesman'],$row['salesman2'],$str);
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        list($insert, $data) = $this->captcha($insert);
        try {
            $this->model->saveAll($insert);
            $this->msg($this->source);
            $this->Export($this->source, $order_sn);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('', '', $data);
    }

    /**
     * phpexcel 时间转换
     * @param $date
     * @param bool $time
     * @return false|int|string
     */
    private function excelTime($date, $time = false)
    {
        //如果是数字则转化，如果是有 - 或者 /，视作文本格式不作处理
        $type1 = strpos($date, '/');
        $type2 = strpos($date, '-');
        if ($type1 || $type2) {
            $return_date = $date;
        } else {
            $return_date = gmdate('Y-m-d H:i:s', \PHPExcel_Shared_Date::ExcelToPHP($date));
        }
        $return_date = strtotime($return_date);
        return $return_date;
    }

    public function importSq()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        $fieldArr['数据来源'] = 'source';//数据来源
        $fieldArr['订单编号'] = 'orderid';//订单编号
        $fieldArr['代理商ID'] = 'agent_id';//订单编号
        $fieldArr['下单时间'] = 'ordertime';//下单时间
        $fieldArr['商品名称'] = 'goods';//商品名称
        $fieldArr['版本'] = 'version';
        $fieldArr['赠品'] = 'gifts';
        $fieldArr['购买数量'] = 'num';//数量
        $fieldArr['收件人姓名'] = 'consignee';//收件人
        $fieldArr['收件人手机'] = 'consigneePhone';//收件人电话
        $fieldArr['收货详细地址'] = 'consigneeAddress';//收件人地址
        $fieldArr['寄件人'] = 'sender';//寄件人
        $fieldArr['备注'] = 'remake';//备注
        $fieldArr['赠品(下册)'] = 'gift';//赠品下册
        Db::startTrans();
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        $order_sn = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $val = trim($val);
                $values[] = is_null($val) ? '' : $val;
            }

            $row = [];
            $temp = array_combine($fields, $values);

            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if (!isset($row['source'])) {
                Db::rollback();
                $this->error(__('数据来源标题错误 ~'));
            }
            if (!isset($row['ordertime'])) {
                Db::rollback();
                $this->error(__('下单时间标题错误 ~'));
            }
            if (!isset($row['sender'])) {
                Db::rollback();
                $this->error(__('寄件人标题错误 ~'));
            }
            if (!isset($row['orderid'])) {
                Db::rollback();
                $this->error(__('订单编号标题错误 ~'));
            }
            if (!isset($row['version'])) {
                Db::rollback();
                $this->error(__('版本标题错误 ~'));
            }
            if (!isset($row['agent_id'])) {
                Db::rollback();
                $this->error(__('代理商标题错误 ~'));
            }
            if (isset($row['gift'])) {
                if ($row['gift'] == '未赠') {
                    $row['gift'] = 1;
                } elseif($row['gift'] == '已赠') {
                    $row['gift'] = 2;
                }else{
                    $row['gift'] = 1;
                }
            }else{
                $row['gift'] = 1;
            }
            if ($row['orderid']) {
                if(!$agentRow = Agent::get($row['agent_id']))
                {
                    Db::rollback();
                    $this->error(__('代理商不存在 ~'));
                }
//                $row['orderid'] = $this->decimalNotation($row['orderid']);
                $row['remake'] = $this->filter_Emoji($row['remake']);
                $row['deliveryForm'] = '韵达快递';
                $row['ordertime'] = $row['ordertime'] ? $this->excelTime($row['ordertime']) : '';
                $order_sn[] = $row['orderid'];
                $row['delivery'] = '待发货';//发货情况
                $row['operator'] = $this->auth->userid;//导入人
                $insert[] = $row;
                $this->source = $row['source'];
            }
        }
        if (!$insert) {
            Db::rollback();
            $this->error(__('No rows were updated'));
        }
        list($insert, $data) = $this->captcha($insert);
        try {
            $this->model->saveAll($insert);
            $this->msg($this->source);
            $this->Export($this->source, $order_sn);
            Db::commit();
        } catch (\think\exception\PDOException $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success('', '', $data);
    }

    /*还原科学计数*/
    public function decimalNotation($num)
    {
        $parts = explode('E', $num);
        if (count($parts) != 2) {
            return $num;
        }
        $exp = abs(end($parts)) + 3;
        $decimal = number_format($num, $exp, '.', '');
        $decimal = rtrim($decimal, '0');

        return rtrim($decimal, '.');
    }

    public function importTb()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['订单编号'] = 'orderid';//订单编号
        $fieldArr['支付单号'] = 'pay_nb';//商户订单号
        $fieldArr['收货人姓名'] = 'consignee';//收件人
        $fieldArr['联系手机'] = 'consigneePhone';//收件人电话
        $fieldArr['收货地址 '] = 'consigneeAddress';//收件人地址
        $fieldArr['宝贝标题 '] = 'goods';//商品名称
        $fieldArr['宝贝总数量'] = 'num';//数量
        $fieldArr['买家应付货款'] = 'amount';//金额
        $fieldArr['买家应付邮费'] = 'courierFees';//快递费用
        $fieldArr['物流公司'] = 'deliveryForm';//快递形式
        $fieldArr['订单备注'] = 'salesman';//业务员
        $fieldArr['物流单号 '] = 'courierBut';//快递单号
        $fieldArr['买家实际支付金额'] = 'alipay';//支付宝
        $fieldArr['订单创建时间'] = 'ordertime';//订单创建时间
        $fieldArr['订单付款时间 '] = 'paytime';//支付时间

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        $order_sn = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }

            $row = [];
            $temp = array_combine($fields, $values);

            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if (!isset($row['pay_nb'])) {
                $this->error(__('请导入淘宝的订单！'));
            }
            if ($row) {
                $row['orderid'] = substr($row['orderid'], 2, 18);
                $row['pay_nb'] = substr($row['pay_nb'], 2, 28);
                $row['ordertime'] = $row['ordertime'] ? $this->excelTime($row['ordertime']) : '';
                $row['paytime'] = $row['paytime'] ? $this->excelTime($row['paytime']) : '';
                $row['source'] = '淘宝';
                $row['agent_id'] = '80';
                $this->source = '淘宝';
                $row['operator'] = $this->auth->userid;//导入人
                $order_sn[] = $row['orderid'];
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        list($insert, $data) = $this->captcha($insert);
        try {
            $this->model->saveAll($insert);
            $this->msg($this->source);
            $this->Export($this->source, $order_sn);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('', '', $data);
    }

    public function importJd()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['订单号'] = 'orderid';//订单编号
        $fieldArr['商品名称'] = 'goods';//商品名称
        $fieldArr['订购数量'] = 'num';//数量
        $fieldArr['应付金额'] = 'amount';//金额
        $fieldArr['客户姓名'] = 'consignee';//收件人
        $fieldArr['联系电话'] = 'consigneePhone';//收件人电话
        $fieldArr['客户地址'] = 'consigneeAddress';//收件人地址
        $fieldArr['运费金额'] = 'courierFees';//快递费用
        $fieldArr['商家备注'] = 'salesman';//业务员
        $fieldArr['结算金额'] = 'payments';//结算金额
        $fieldArr['支付方式'] = 'payment';//支付方式
        $fieldArr['订单状态'] = 'delivery';//发货情况
        $fieldArr['订单备注'] = 'remake';//备注
        $fieldArr['下单时间'] = 'ordertime';//下单时间
        $fieldArr['付款确认时间'] = 'paytime';//付款确认时间

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        $order_sn = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }

            $row = [];
            $temp = array_combine($fields, $values);

            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if (strlen($row['orderid']) > 12) {
                $this->error(__('请导入京东的订单！'));
            }
            if ($row) {
                $row['payment'] .= $row['payments'];
                $row['source'] = '京东';
                $row['agent_id'] = '79';
                $this->source = '京东';
                $row['ordertime'] = $row['ordertime'] ? $this->excelTime($row['ordertime']) : '';
                $row['paytime'] = $row['paytime'] ? $this->excelTime($row['paytime']) : '';
                unset($row['payments']);
                $order_sn[] = $row['orderid'];
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        list($insert, $data) = $this->captcha($insert);
        try {
            $this->model->saveAll($insert);
            $this->msg($this->source);
            $this->Export($this->source, $order_sn);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('', '', $data);
    }

    public function importWd()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['订单编号'] = 'orderid';//订单编号
        $fieldArr['收件人姓名'] = 'consignee';//收件人
        $fieldArr['收件人手机'] = 'consigneePhone';//收件人电话
        $fieldArr['收货详细地址'] = 'consigneeAddress';//收件人地址
        $fieldArr['商品名称'] = 'goods';//商品名称
        $fieldArr['商品型号'] = 'version';//商品名称
        $fieldArr['商品总件数'] = 'num';//数量
        $fieldArr['商品原价'] = 'amount';//金额
        $fieldArr['赠品'] = 'gifts';//赠品
        $fieldArr['运费'] = 'courierFees';//快递费用
        $fieldArr['物流公司'] = 'deliveryForm';//快递形式
        $fieldArr['买家留言'] = 'remake';//买家留言
        $fieldArr['物流单号'] = 'courierBut';//快递单号
        $fieldArr['订单金额（不含退款）'] = 'wechat';//微信
        $fieldArr['订单状态'] = 'orderStatus';//订单状态
        $fieldArr['分销店铺名称'] = 'reseller';//分销店铺名称
        $fieldArr['分销商手机号'] = 'resellerPhone';//分销商手机号
        $fieldArr['下单时间'] = 'ordertime';//创建时间
        $fieldArr['付款时间'] = 'paytime';//付款时间
        $fieldArr['数据来源'] = 'source';//数据来源

        //source 来源

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        $order_sn = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }

            $row = [];
            $temp = array_combine($fields, $values);

            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if ($row) {
                $arr = explode(';', $row['amount']);
                if (count($arr) > 1) {
                    $row['amount'] = 0;
                    for ($i = 0; $i < count($arr); $i++) {
                        $row['amount'] += $arr[$i];
                    }
                }
                $row['remake'] = $this->filter_Emoji($row['remake']);
                $row['ordertime'] = $row['ordertime'] ? $this->excelTime($row['ordertime']) : '';
                $row['paytime'] = $row['paytime'] ? $this->excelTime($row['paytime']) : '';
                $order_sn[] = $row['orderid'];
                $row['operator'] = $this->auth->userid;//导入人
                $row['source'] = '微店';
                $insert[] = $row;
                $this->source = $row['source'];
            }
        }
        if (!isset($row['reseller'])) {
            $this->error(__('请导入微店的订单！'));
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        list($insert, $data) = $this->captcha($insert);
        try {
            $this->model->saveAll($insert);
            $this->msg($this->source);
            $this->Export($this->source, $order_sn);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success('', '', $data);
    }

    public function filter_Emoji($str)
    {
        $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }

    /**
     * 订单号是否存在
     * @param array $array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function captcha(array $array)
    {
        $array2 = [];
        foreach ($array as $key => $value) {
            if ($row = $this->model->where('orderid', $value['orderid'])->find()) {
                $array2[] = $value;
                unset($array[$key]);
            }
        }
        return [$array, $array2];
    }

    protected function Excle($ids = 0)
    {
        $where['id'] = ['in', $ids];
        $list = collection($this->model->where($where)->select())->toArray();
        $objPHPExcel = new PHPExcel();
        //设置每列的标题
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '下单日期')
            ->setCellValue('B1', '存货编码')
            ->setCellValue('C1', '单价')
            ->setCellValue('D1', '金额')
            ->setCellValue('E1', '数量')
            ->setCellValue('F1', '订单编号')
            ->setCellValue('G1', '数据来源')
            ->setCellValue('H1', '代理商ID')
            ->setCellValue('I1', '商品名称')
            ->setCellValue('J1', '版本')
            ->setCellValue('K1', 'A学习书')
            ->setCellValue('L1', 'B练习书')
            ->setCellValue('M1', 'C素材书')
            ->setCellValue('N1', '字词句手册')
            ->setCellValue('O1', '年级阅读')
            ->setCellValue('P1', '教案')
            ->setCellValue('Q1', '数学')
            ->setCellValue('R1', '数量')
            ->setCellValue('S1', '金额')
            ->setCellValue('T1', '收件人')
            ->setCellValue('U1', '收件人电话')
            ->setCellValue('V1', '收件人地址')
            ->setCellValue('W1', '快递方式')
            ->setCellValue('X1', '快递单号')
            ->setCellValue('Y1', '订单状态')
            ->setCellValue('Z1', '备注');
        //存取数据  这边是关键

        foreach ($list as $k => $v) {
            if($v['ordertime'] > 100)
            {
                $ordertime = date('Y-m-d',$v['ordertime']);
            }else{
                $ordertime = $v['ordertime'];
            }
            $num = $k + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $num, $ordertime)
                ->setCellValue('B' . $num, '')
                ->setCellValue('C' . $num, '')
                ->setCellValue('D' . $num, $v['amount'])
                ->setCellValue('E' . $num, '')
                ->setCellValueExplicit('F' . $num, $v['orderid'])
                ->setCellValue('G' . $num, $v['source'])
                ->setCellValue('H' . $num, $v['agent_id'])
                ->setCellValue('I' . $num, $v['goods'])
                ->setCellValue('J' . $num, $v['version'] . $v['gifts'])
                ->setCellValue('K' . $num, '')
                ->setCellValue('L' . $num, '')
                ->setCellValue('M' . $num, '')
                ->setCellValue('N' . $num, '')
                ->setCellValue('O' . $num, '')
                ->setCellValue('P' . $num, '')
                ->setCellValue('Q' . $num, '')
                ->setCellValue('R' . $num, $v['num'])
                ->setCellValue('S' . $num, $v['amount'])
                ->setCellValue('T' . $num, $v['consignee'])
                ->setCellValue('U' . $num, $v['consigneePhone'])
                ->setCellValue('V' . $num, $v['consigneeAddress'])
                ->setCellValue('W' . $num, $v['deliveryForm'])
                ->setCellValueExplicit('X' . $num, '')
                ->setCellValue('Y' . $num, $v['orderStatus'])
                ->setCellValue('Z' . $num, ' '.$v['remake']." ");
//                ->setCellValue('S' . $num, $v['courierBut'])
            $objSheet = $objPHPExcel->getActiveSheet();
            $objSheet->getColumnDimension('A')->setWidth(20); //设置列宽
            $objSheet->getColumnDimension('B')->setWidth(20);
            $objSheet->getColumnDimension('D')->setWidth(30);
            $objSheet->getColumnDimension('E')->setWidth(30);
            $objSheet->getColumnDimension('F')->setWidth(15);
            $objSheet->getColumnDimension('G')->setWidth(20);
            $objSheet->getColumnDimension('H')->setWidth(20);
            $objSheet->getColumnDimension('I')->setWidth(30);
            $objSheet->getColumnDimension('J')->setWidth(30);
            $objSheet->getColumnDimension('K')->setWidth(15);
            $objSheet->getColumnDimension('L')->setWidth(15);
            $objSheet->getColumnDimension('M')->setWidth(15);
            $objSheet->getColumnDimension('N')->setWidth(15);
            $objSheet->getColumnDimension('O')->setWidth(15);
            $objSheet->getColumnDimension('P')->setWidth(15);
            $objSheet->getColumnDimension('Q')->setWidth(15);
            $objSheet->getColumnDimension('R')->setWidth(15);
            $objSheet->getColumnDimension('S')->setWidth(15);
            $objSheet->getColumnDimension('T')->setWidth(15);
            $objSheet->getColumnDimension('U')->setWidth(40);
            $objSheet->getColumnDimension('V')->setWidth(15);
            $objSheet->getColumnDimension('W')->setWidth(15);
            $objSheet->getColumnDimension('X')->setWidth(15);
            $objSheet->getColumnDimension('Y')->setWidth(15);
            $objSheet->getColumnDimension('Z')->setWidth(15);
            $objSheet->getRowDimension($num)->setRowHeight(17); //设置行高

        }

        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(4)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(5)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(6)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(7)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(9)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(10)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(11)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(12)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(13)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(14)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(15)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(16)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(17)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(18)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(19)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(20)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(21)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(22)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(23)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(24)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(25)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(26)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(27)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(28)->setRowHeight(17);

        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName("微软雅黑")->setSize(12);
        //标题字体
        $objPHPExcel->getActiveSheet()->getStyle("A1:Z1")->getFont()->setSize(12)->setBold(true);
        //设置列的宽度
//        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
//        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->setActiveSheetIndex(0);

        //水平居中
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //单元个居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:Z1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $date = date('Y-m-dhis', time());
        $objWriter->save('./agent/xlsx/' . $this->auth->username  . $date . '.xlsx');
        return $path = '/agent/xlsx/' . $this->auth->username  . $date . '.xlsx';
    }

    protected function Export($source, array $orderArr)
    {
        return false;
        $orderArr = implode(',', $orderArr);
        $where['orderid'] = ['in', $orderArr];
        $list = collection($this->model->where($where)->select())->toArray();
        $objPHPExcel = new PHPExcel();
        //设置每列的标题
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '下单日期')
            ->setCellValue('B1', '存货编码')
            ->setCellValue('C1', '单价')
            ->setCellValue('D1', '金额')
            ->setCellValue('E1', '数量')
            ->setCellValue('F1', '订单编号')
            ->setCellValue('G1', '数据来源')
            ->setCellValue('H1', '代理商ID')
            ->setCellValue('I1', '商品名称')
            ->setCellValue('J1', '版本')
            ->setCellValue('K1', 'A学习书')
            ->setCellValue('L1', 'B练习书')
            ->setCellValue('M1', 'C素材书')
            ->setCellValue('N1', '字词句手册')
            ->setCellValue('O1', '年级阅读')
            ->setCellValue('P1', '教案')
            ->setCellValue('Q1', '数学')
            ->setCellValue('R1', '数量')
            ->setCellValue('S1', '金额')
            ->setCellValue('T1', '收件人')
            ->setCellValue('U1', '收件人电话')
            ->setCellValue('V1', '收件人地址')
            ->setCellValue('W1', '快递方式')
            ->setCellValue('X1', '快递单号')
            ->setCellValue('Y1', '订单状态')
            ->setCellValue('Z1', '备注');
        //存取数据  这边是关键
        foreach ($list as $k => $v) {
            $num = $k + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $num, date('Y-m-d',$v['ordertime']))
                ->setCellValue('B' . $num, '')
                ->setCellValue('C' . $num, '')
                ->setCellValue('D' . $num, $v['amount'])
                ->setCellValue('E' . $num, '')
                ->setCellValueExplicit('F' . $num, $v['orderid'])
                ->setCellValue('G' . $num, $v['source'])
                ->setCellValue('H' . $num, $v['agent_id'])
                ->setCellValue('I' . $num, $v['goods'])
                ->setCellValue('J' . $num, $v['version'] . $v['gifts'])
                ->setCellValue('K' . $num, '')
                ->setCellValue('L' . $num, '')
                ->setCellValue('M' . $num, '')
                ->setCellValue('N' . $num, '')
                ->setCellValue('O' . $num, '')
                ->setCellValue('P' . $num, '')
                ->setCellValue('Q' . $num, '')
                ->setCellValue('R' . $num, $v['num'])
                ->setCellValue('S' . $num, $v['amount'])
                ->setCellValue('T' . $num, $v['consignee'])
                ->setCellValue('U' . $num, $v['consigneePhone'])
                ->setCellValue('V' . $num, $v['consigneeAddress'])
                ->setCellValue('W' . $num, $v['deliveryForm'])
                ->setCellValueExplicit('X' . $num, '')
                ->setCellValue('Y' . $num, $v['orderStatus'])
                ->setCellValue('Z' . $num, '`'.$v['remake'].'`');
//                ->setCellValue('S' . $num, $v['courierBut'])
            $objSheet = $objPHPExcel->getActiveSheet();
            $objSheet->getColumnDimension('A')->setWidth(20); //设置列宽
            $objSheet->getColumnDimension('B')->setWidth(20);
            $objSheet->getColumnDimension('D')->setWidth(30);
            $objSheet->getColumnDimension('E')->setWidth(30);
            $objSheet->getColumnDimension('F')->setWidth(15);
            $objSheet->getColumnDimension('G')->setWidth(20);
            $objSheet->getColumnDimension('H')->setWidth(20);
            $objSheet->getColumnDimension('I')->setWidth(30);
            $objSheet->getColumnDimension('J')->setWidth(30);
            $objSheet->getColumnDimension('K')->setWidth(15);
            $objSheet->getColumnDimension('L')->setWidth(15);
            $objSheet->getColumnDimension('M')->setWidth(15);
            $objSheet->getColumnDimension('N')->setWidth(15);
            $objSheet->getColumnDimension('O')->setWidth(15);
            $objSheet->getColumnDimension('P')->setWidth(15);
            $objSheet->getColumnDimension('Q')->setWidth(15);
            $objSheet->getColumnDimension('R')->setWidth(15);
            $objSheet->getColumnDimension('S')->setWidth(15);
            $objSheet->getColumnDimension('T')->setWidth(15);
            $objSheet->getColumnDimension('U')->setWidth(40);
            $objSheet->getColumnDimension('V')->setWidth(15);
            $objSheet->getColumnDimension('W')->setWidth(15);
            $objSheet->getColumnDimension('X')->setWidth(15);
            $objSheet->getColumnDimension('Y')->setWidth(15);
            $objSheet->getColumnDimension('Z')->setWidth(15);
            $objSheet->getRowDimension($num)->setRowHeight(17); //设置行高

        }

        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(4)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(5)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(6)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(7)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(9)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(10)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(11)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(12)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(13)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(14)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(15)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(16)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(17)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(18)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(19)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(20)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(21)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(22)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(23)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(24)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(25)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(26)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(27)->setRowHeight(17);
        $objPHPExcel->getActiveSheet()->getRowDimension(28)->setRowHeight(17);

        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName("微软雅黑")->setSize(12);
        //标题字体
        $objPHPExcel->getActiveSheet()->getStyle("A1:Z1")->getFont()->setSize(12)->setBold(true);
        //设置列的宽度
//        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
//        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->setActiveSheetIndex(0);

        //水平居中
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //单元个居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:Z1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $date = date('Y-m-d', time());
        $objWriter->save('./agent/xlsx/' . $this->auth->username . '[' . $source . ']' . $date . '.xlsx');
        //上传到企业微信临时文件

        $config = Assistant::config();
        $app = Factory::work($config);
        $path = ROOT_PATH . 'public/agent/xlsx/' . $this->auth->username . '[' . $source . ']' . $date . '.xlsx';
        $res = $app->media->uploadFile($path);
        //发送文件给操作人
        if ($res['errcode'] == 0) {
            unlink($path);
            $token = $app->access_token->getToken();//获取企业微信token

            $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
            $params = [
                'touser' => $this->toUser,
                'msgtype' => 'file',
                'agentid' => $config['agent_id'],
                'file' => [
                    'media_id' => $res['media_id']
                ],
                'safe' => 0
            ];
            $response = \fast\Http::post($url, json_encode($params));
        }

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                if(isset($values['Excle']))
                {
                    //导出表格
                    $url = $this->Excle($ids);
                    $this->success('导出成功,如果数据比较多，请耐心等待！<script>window.open("'.$url.'");</script>');
                }else{
                    $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                    if ($values) {
                        $msg = $this->SmsData($ids,$values);
                        $this->success($msg);
                    } else {
                        $this->error(__('You have no permission'));
                    }
                }

            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    protected function SmsData($ids,$values)
    {
        $success = 0;
        $error = 0;
        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        foreach ($list as $index => $item) {
            $smsData = [];
            $smsData['phone'][] = $item['consigneePhone'];
            $smsData['sign'][] = '宏达一甲';
            switch ($values['status']){
                case 0:
                    //已发货通知 （拆分包裹的情况）
                    $moban = 'SMS_181868543';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut']];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 1:
                    //已发货通知 （未拆分包裹，未缺书的情况）
                    $moban = 'SMS_182550797';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut']];
                    $content = "《小学生绘本课堂》已发货,根据随书附带的流程，下载APP配合使用效果最佳！个别包裹超重，故拆分发货，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 2:
                    //已发货通知 （缺书「学习书」）
                    $moban = 'SMS_182550800';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodName'=>'学习书'];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因学习书缺货，于一周内为您补寄，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 3:
                    //已发货通知 （缺书「练习书」）
                    $moban = 'SMS_182550800';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodName'=>'练习书'];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因练习书缺货，于一周内为您补寄，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 4:
                    //已发货通知 （缺书「素材书」）
                    $moban = 'SMS_182550800';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodName'=>'素材书'];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因素材书缺货，于一周内为您补寄，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 5:
                    //已发货通知 （缺书「年级阅读 」）
                    $moban = 'SMS_182550800';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodName'=>'年级阅读'];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因年级阅读缺货，于一周内为您补寄，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 6:
                    //已发货通知 （缺书「字词句手册」）
                    $moban = 'SMS_182550800';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodName'=>'字词句手册'];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因字词句手册缺货，于一周内为您补寄，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 7:
                    //已发货通知 （缺书「教案」）
                    $moban = 'SMS_182550800';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodName'=>'教案'];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因教案缺货，于一周内为您补寄，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 8:
                    //已发货通知 （缺书「数学」）
                    $moban = 'SMS_182550800';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodName'=>'数学'];
                    $content = "《小学生绘本课堂》已发货，根据随书附带的流程，下载APP配合使用效果更佳！因数学缺货，于一周内为您补寄，盼理解。快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 9:
                    //已发货通知 （补寄「学习书」）
                    $moban = 'SMS_182540804';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodsName'=>'学习书'];
                    $content = "《小学生绘本课堂》为您补寄的学习书已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 10:
                    //已发货通知 （补寄「练习书」）
                    $moban = 'SMS_182540804';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodsName'=>'练习书'];
                    $content = "《小学生绘本课堂》为您补寄的练习书已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 11:
                    //已发货通知 （补寄「素材书」）
                    $moban = 'SMS_182540804';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodsName'=>'素材书'];
                    $content = "《小学生绘本课堂》为您补寄的素材书已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 12:
                    //已发货通知 （补寄「年级阅读 」）
                    $moban = 'SMS_182540804';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodsName'=>'年级阅读'];
                    $content = "《小学生绘本课堂》为您补寄的年级阅读已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 13:
                    //已发货通知 （补寄「字词句手册」）
                    $moban = 'SMS_182540804';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodsName'=>'字词句手册'];
                    $content = "《小学生绘本课堂》为您补寄的字词句手册已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 14:
                    //已发货通知 （补寄「教案」）
                    $moban = 'SMS_182540804';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodsName'=>'教案'];
                    $content = "《小学生绘本课堂》为您补寄的教案已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;
                case 15:
                    //已发货通知 （补寄「数学」）
                    $moban = 'SMS_182540804';
                    $smsData['template'][] = ['kuaidi_name'=>$item['deliveryForm'],'order_sn'=>$item['courierBut'],'goodsName'=>'数学'];
                    $content = "《小学生绘本课堂》为您补寄的数学已发货，根据随书附带的流程，下载APP配合使用效果更佳！快递方式：{$item['deliveryForm']}，快递单号：{$item['courierBut']}。";
                    break;

            }
            AliyunSendSms::$templateCode = $moban;
            $response = AliyunSendSms::sendSms($smsData);
            if($response->Code == 'OK')
            {
                //添加成功记录
                ManagementSms::create([
                    'management_id'=>$item->id,
                    'content'=>$content,
                    'send'=>1
                ]);
                $success++;
            }else{
                $why = __($response->Code);
                $why .=','.$response->Message;
                //添加失败记录
                ManagementSms::create([
                    'management_id'=>$item->id,
                    'content'=>$content,
                    'send'=>2,
                    'why'=>$why
                ]);
                $error++;
            }
            $item->allowField(true)->isUpdate(true)->save(['send'=>$item->send+1]);
        }
        return "成功：$success 条,失败 $error 条";
    }

    /**
     * 判断分类对不对
     * @param $code
     * @param $kemu
     * @return bool
     * @throws \think\exception\DbException
     */
    protected function getAuthType($code,$kemu)
    {
        $code = str_replace("-", "", str_replace(" ", '', trim($code)));
        $codeArr = array_unique(explode(',',$code));
        foreach ($codeArr as $value)
        {
            if(!$kemu)
            {
                if(!$row = Serial::get(['code'=>$value,'send'=>0])) return false;
                if(!in_array($row['kemu'],[23,24,25,26,27,28,29,30,31,32,33,34])) return false;
            }else{
                if(!Serial::get(['banben'=>$kemu,'code'=>$value,'send'=>0])) return false;
            }
        }
        return $codeArr;
    }

    /**
     * 字词句手册验证添加
     * @param null $code
     */
    protected function wordWords($code = null,$banben = '')
    {
        $code = str_replace("-", "", str_replace(" ", '', trim($code)));
        $codeArr = array_unique(explode(',',$code));
        foreach ($codeArr as $value)
        {
            if(!$row = Serial::get(['code'=>$value])){
                Serial::create([
                    'code'=>$value,
                    'product'=>'35',
                    'kemu'=>'11',
                    'banben'=>'16',
                    'type'=>'8,9,28',
                ]);
            }else{
                if($row['banben'] != $banben){
                    $newkeyStr= substr($value, 0, 3);
                    $newkey= $newkeyStr . '-' . substr($value, 3, 5). '-' . substr($value, 8);
                    $this->error($newkey.'不是字词句手册！','','',8);
                }
            }
        }
    }
    /**
     * 上册序列号验证添加
     * @param null $code
     */
    protected function insert_sc($code = null,$kemu='',$banben = '',$type= '')
    {
        $code = str_replace("-", "", str_replace(" ", '', trim($code)));

        if(!$row = Serial::get(['code'=>$code])){
            Serial::create([
                'code'=>$code,
                'product'=>'35',
                'kemu'=>$kemu,
                'banben'=>$banben,
                'type'=>$type,
            ]);
        }
    }
    /**
     * 上册序列号获取分类
     * @param null $code
     */
    protected function gettype_sc($subject=null,$kemu)
    {
        switch($subject){
            case 11:
                if($kemu==11){
                    return $type="8,9,23";
                }elseif($kemu==12){
                    return $type="8,9,24";
                }elseif($kemu==13){
                    return $type="8,9,25";
                }elseif($kemu==14){
                    return $type="8,9,26";
                }elseif($kemu==15){
                    return $type="8,9,27";
                }elseif($kemu==11){
                    return $type="8,9,28";
                }
                break;
            case 13:
                if($kemu==11){
                    return $type="8,38,39";
                }elseif($kemu==12){
                    return $type="8,38,40";
                }elseif($kemu==13){
                    return $type="8,38,41";
                }elseif($kemu==14){
                    return $type="8,38,42";
                }elseif($kemu==15){
                    return $type="8,38,43";
                }elseif($kemu==11){
                    return $type="8,38,44";
                }
                break;
            case 15:
                if($kemu==11){
                    return $type="8,52,53";
                }elseif($kemu==12){
                    return $type="8,52,54";
                }elseif($kemu==13){
                    return $type="8,52,55";
                }elseif($kemu==14){
                    return $type="8,52,56";
                }elseif($kemu==15){
                    return $type="8,52,57";
                }elseif($kemu==11){
                    return $type="8,52,58";
                }
                break;
            case 17:
                if($kemu==11){
                    return $type="8,66,67";
                }elseif($kemu==12){
                    return $type="8,66,68";
                }elseif($kemu==13){
                    return $type="8,66,69";
                }elseif($kemu==14){
                    return $type="8,66,70";
                }elseif($kemu==15){
                    return $type="8,66,71";
                }elseif($kemu==11){
                    return $type="8,66,72";
                }
                break;
            case 19:
                if($kemu==11){
                    return $type="8,80,81";
                }elseif($kemu==12){
                    return $type="8,80,82";
                }elseif($kemu==13){
                    return $type="8,80,83";
                }elseif($kemu==14){
                    return $type="8,80,84";
                }elseif($kemu==15){
                    return $type="8,80,85";
                }elseif($kemu==11){
                    return $type="8,80,86";
                }
                break;
            case 21:
                if($kemu==11){
                    return $type="8,94,95";
                }elseif($kemu==12){
                    return $type="8,94,96";
                }elseif($kemu==13){
                    return $type="8,94,97";
                }elseif($kemu==14){
                    return $type="8,94,98";
                }elseif($kemu==15){
                    return $type="8,94,99";
                }elseif($kemu==11){
                    return $type="8,94,100";
                }
                break;
        }
    }
    public function getAddress($address)
    {
        $address = urlencode($address);
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key=HRABZ-YBNW5-5IPIE-QYAY4-7FOP2-2LBID";
        $result = json_decode(\fast\Http::get($url), true);
        if($result['status'] != 0 )
        {
            if($result['status'] == 347)
            {
                $this->error('收货地址错的太离谱了！找不到这个地址:'.urldecode($address));
            }
            $result = $this->getAddress($address);
        }
        return $result;
    }
}


